import path from 'node:path'
import { fileURLToPath } from 'node:url'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { defineConfig } from 'vite'
import svgLoader from 'vite-svg-loader'
import packageJson from './package.json'
import codeService from 'csdev/vite-plugin'
import type { AliasOptions } from 'vite'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const pathResolve = (directory: string) => {
  return path.resolve(dirname, '.', directory)
}

const alias: AliasOptions = [
  {
    find: '/@',
    replacement: pathResolve('./src/')
  }
]

const viteConfig = defineConfig(() => {
  return {
    plugins: [
      vue(),
      vueJsx(),
      svgLoader(),
      codeService()
    ],
    root: process.cwd(),
    resolve: { alias },
    optimizeDeps: {
      include: []
    },
    server: {
      host: '0.0.0.0',

      // origin: base, //项目baseUrl，解决主应用中出现静态地址404问题
      // open: true, // 启动服务后自动打开浏览器
      hmr: true,
      port: packageJson.port,
      proxy: {
        '/api': {
          target: 'https://mgwtest.csair.com',
          ws: true,
          changeOrigin: true,
          rewrite: proxyPath => proxyPath.replace(/^\/api/, ''),
          // 登录后手动把https://kpitest.csair.com/slogin 的 session放到cookie里
          headers: {
            Cookie:
              'SESSION=0413bf7a-0b01-472d-8454-edd19ab35de8'
          }
        }
      }
    },
    build: {
      outDir: 'dist',
      sourcemap: true,

      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          entryFileNames: 'assets/js/entry.[name].[hash].js',
          chunkFileNames: 'assets/js/chunk.[name].[hash].js',
          assetFileNames: 'assets/[ext]/[name].[hash].[ext]',
          compact: true,
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia'],
            'element-plus': ['element-plus', '@element-plus/icons-vue'],
            echarts: ['echarts'],
            'csui-other': [
              'hls.js',
              'dplayer',
              'dayjs',
              'clipboard-copy',
              'vue3-tree-org',
              'vue-dompurify-html',
              'lodash-unified',
              'resize-observer-polyfill'
            ],
            csui: ['csui']
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        css: { charset: false }
      }
    },
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(true),
      __VUE_I18N_LEGACY_API__: JSON.stringify(false),
      __VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
      __INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
      __VERSION__: JSON.stringify(process.env.npm_package_version)
    }
  }
})

export default viteConfig
